package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JCheckBox;
import javax.swing.JPanel;

import ui.BusyDialog;
import model.Database;
import model.EmpTableModel;
import model.Employee;
import model.IOFile;
import model.OptionMessenger;
import model.UICommand;
import view.EmployeePanel;

public class EmployeeController extends MouseAdapter implements ActionListener {
	private EmployeePanel view;
	private Connection connect;
	private boolean isModify;
	private EmpTableModel tableModel;

	public EmployeeController(EmpTableModel tableModel) {
		this.tableModel = tableModel;
		this.view = new EmployeePanel(tableModel, this);
		this.isModify = false;
	}

	// TODO action
	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();

		switch (cmd) {
		case UICommand.ADD_CMD:
			if (isModify)
				update();
			else
				addEmpl();
			break;
		case UICommand.SHOW_CMD: // show panel display information
			isModify = false;
			view.enableTable(false);
			view.setTextButtonAdd("Thêm");
			int maxId = tableModel.getMaxIDEmpl();
			maxId++;
			view.setText(maxId + "");
			view.editable(true);
			view.showPanelFunc(true);
			view.setCollapsedTaskpane(false);
			break;
		case UICommand.DELETE_CMD:
			if (view.getSelectedRealRows().length == 0) {
				OptionMessenger.showMessageDialog(
						OptionMessenger.windowForComponent(view),
						"Chọn nhân viên cần xóa", "Thông báo",
						OptionMessenger.QUESTION_MESSAGE);
			} else {
				if ((OptionMessenger.showQuestionDialog(
						OptionMessenger.windowForComponent(view),
						"Bạn có chắc muốn xóa nhân viên này?", "Cảnh báo",
						OptionMessenger.WARNING_MESSAGE)) == OptionMessenger.OK_OPTION) {
					delete();
				}
			}
			break;
		case UICommand.MODIFY_CMD:
			if (view.getSelectedRealRows().length == 0) {
				OptionMessenger.showMessageDialog(
						OptionMessenger.windowForComponent(view),
						"Chọn thông tin nhân viên cần thay đổi", "Thông báo",
						OptionMessenger.WARNING_MESSAGE);
			} else {
				isModify = true;
				view.setTextButtonAdd("Lưu");
				view.editable(true);
				view.showPanelFunc(true);
				view.setCollapsedTaskpane(false);
			}
			break;
		case UICommand.RELOAD_CMD: // reload data
			view.clearSelectionTable();
			view.cancel();
			ActionListener action = new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					tableModel.loadData();
				}
			};
			BusyDialog.showBusyDialog(OptionMessenger.windowForComponent(view),
					"Tải lại dữ liệu", action, null);
			break;
		case UICommand.CANCEL_CMD:
			view.cancel();
			break;
		case "test":
			JCheckBox checkBox = (JCheckBox)e.getSource();
			view.enableTextField(checkBox.getName(), checkBox.isSelected());
			break;
		}
	}

	// delete employee
	private void delete() {
		try {
			connect = Database.connect();
			PreparedStatement preStm = connect
					.prepareStatement("DELETE FROM employee WHERE id_empl = ?");

			int[] realRows = view.getSelectedRealRows();
			for (int i = 0; i < realRows.length; i++) {
				Employee empl = (Employee) tableModel.getRow(realRows[i]);

				preStm.setInt(1, empl.getId());
				preStm.execute();
			}
			view.setText("");
			tableModel.loadData();
		} catch (SQLException e) {
			e.printStackTrace(IOFile.getInstance());
		} catch (ClassNotFoundException e) {
			e.printStackTrace(IOFile.getInstance());
		}
	}

	// TODO update information the employee
	private void update() {
		if ((OptionMessenger.showQuestionDilog(
				OptionMessenger.windowForComponent(view),
				"Bạn có muốn thay đổi thông tin nhân viên này không?",
				"Cảnh báo", OptionMessenger.QUESTION_MESSAGE, 0)) == OptionMessenger.OK_OPTION) {
			try {
				connect = Database.connect();
				PreparedStatement preStm = connect
						.prepareStatement("UPDATE employee SET first_name =?,last_name=?,birthday=?,sex=?,identification=?,address=?,phone=?,date_begin=?,regency=? WHERE id_empl=?");

				String[] empl = view.getInfor();
				for (int i = 0; i < empl.length; i++) {
					if (i != 0)
						preStm.setString(i, empl[i]);
					else
						preStm.setString(10, empl[i]);
				}
				preStm.executeUpdate();
				tableModel.loadData();

				view.showPanelFunc(false);
				view.editable(false);
			} catch (SQLException e) {
				e.printStackTrace(IOFile.getInstance());
				OptionMessenger.showMessageDialog(
						OptionMessenger.windowForComponent(view),
						e.getMessage(), "Lỗi", OptionMessenger.ERROR_MESSAGE);
			} catch (ClassNotFoundException e) {
				e.printStackTrace(IOFile.getInstance());
			}
		}
	}

	// TODO add a new employee
	public void addEmpl() {
		if (view.checkNameIsNull()) {
			OptionMessenger.showMessageDialog(
					OptionMessenger.windowForComponent(view),
					"Tên nhân viên không được rỗng", "Lỗi",
					OptionMessenger.ERROR_MESSAGE);
		} else {
			String[] empl = view.getInfor();
			if (isExits(empl[0])) {
				OptionMessenger.showMessageDialog(
						OptionMessenger.windowForComponent(view),
						"Mã nhân viên đã tồn tại", "Lỗi",
						OptionMessenger.ERROR_MESSAGE);
				view.editTxtId(true);
			} else {
				try {
					PreparedStatement pre = connect
							.prepareStatement("INSERT INTO employee VALUES(?,?,?,?,?,?,?,?,?,?)");
					for (int i = 0; i < empl.length; i++) {
						pre.setString(i + 1, empl[i]);
					}
					pre.executeUpdate();
					tableModel.loadData();
					view.cancel();
					OptionMessenger.showMessageDialog(
							OptionMessenger.windowForComponent(view),
							"Thêm nhân viên thành công", "Tin nhắn",
							OptionMessenger.PLAIN_MESSAGE);
				} catch (SQLException e) {
					e.printStackTrace(IOFile.getInstance());
					OptionMessenger.showMessageDialog(
							OptionMessenger.windowForComponent(view),
							e.getMessage(), "Lỗi",
							OptionMessenger.ERROR_MESSAGE);
				}
			}
		}
	}

	// check id employee is exits
	public boolean isExits(String str) {
		try {
			connect = Database.connect();

			PreparedStatement preStm = connect
					.prepareStatement("SELECT * FROM employee WHERE id_empl = ?");
			preStm.setString(1, str);

			ResultSet rs = preStm.executeQuery();
			while (rs.next()) {
				if (rs.getString("id_empl").equalsIgnoreCase(str))
					return true;
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace(IOFile.getInstance());
		} catch (SQLException e) {
			e.printStackTrace(IOFile.getInstance());
		}
		return false;
	}

	public JPanel getView() {
		return this.view;
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		super.mouseReleased(e);
		view.showDetail();
	}

}
